package com.fone.player.sns.impl;

import java.util.HashMap;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.tencent.weibo.TencentWeibo;

import com.fone.player.sns.ISNSLoginManager;
import com.fone.player.sns.bean.SNSUserInfo;
import com.fone.player.sns.util.SNSUtil;
import com.fone.player.sns.util.WebViewUtil;
import com.fone.player.sns.util.WeiXinShareUtil;
import com.fone.player.sns.view.MyAuthorizeAdapter;
import com.fone.player.util.L;

public class SNSLoginManager implements ISNSLoginManager {
	
	private static final String TAG = "SNSLoginManager";
	
	private static final int ONOTHERAUTHIRSUCCESS = 0;
	private static final int ONOTHERAUTHIRCANCLE = 1;
	private static final int ONOTHERAUTHIRERROR = 2;
	private static final int GETUSERINFOSUCCESS = 3;
	
	private static final int STOP_SNS = 4;
	
	private boolean SNSPageOpening = false;
	
	private static Context mContext;
	public AuthorizingStateListener mAuthorizingStateListener;
	
	private Handler mHandler;
	
	private static SNSLoginManager mSNSLoginManager;
	
	private SNSLoginManager(Context context){
		mContext = context;
		initHandler();
	}
	
	public static void iniLoginManagerInstance(Context context){
		mContext = context;
		if(mSNSLoginManager==null){
			mSNSLoginManager = new SNSLoginManager(context);
		}
	}
	
	public static SNSLoginManager getInstance(){
		if(mSNSLoginManager==null){
			throw new IllegalStateException(" SNSLoginManager has not been initialized ");
		}
		return mSNSLoginManager;
	}
	
	@SuppressLint("HandlerLeak")
	private void initHandler() {
		mHandler = new Handler(mContext.getMainLooper()) {

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case ONOTHERAUTHIRSUCCESS:
					if (mAuthorizingStateListener != null) {
						mAuthorizingStateListener.authrizeAction(
								AuthorizingStateListener.AUTHORIZE_SUCCESS,
								"authorize success");
					}
					break;
				case ONOTHERAUTHIRCANCLE:
					if (mAuthorizingStateListener != null){
						mAuthorizingStateListener.authrizeAction(
								AuthorizingStateListener.AUTHORIZE_CANCEL,
								"authoriz cancel");
					}
					break;
				case ONOTHERAUTHIRERROR:
					if (mAuthorizingStateListener != null) {
						mAuthorizingStateListener.authrizeAction(
								AuthorizingStateListener.AUTHORIZE_ERROR,
								"授权失败");
					}
					break;
				case GETUSERINFOSUCCESS:
					if (mAuthorizingStateListener != null) {
						mAuthorizingStateListener
								.onUserInfoComplete((SNSUserInfo)(msg.obj));
					}
					break;
				case STOP_SNS:
					if((!SNSUtil.isSNSPageShowing())&&SNSPageOpening){
						SNSPageOpening = false;
						if(mAuthorizingStateListener!=null&&!SNSUtil.isSNSStop()){
							mAuthorizingStateListener.authrizeAction(
									AuthorizingStateListener.AUTHORIZE_ERROR,
									"网络超时,请稍后重试");
						}
						SNSUtil.stopSNS();
					}
					break;
				default:
					break;
				}
			}
		};
	}
	
	@Override
	public void setAuthiringStateListener(
			AuthorizingStateListener authorizingStateListener) {
		mAuthorizingStateListener = authorizingStateListener;
		
	}

	@Override
	public AuthorizingStateListener getAuthiringStateListener() {
		return mAuthorizingStateListener;
	}
	
	@Override
	public void authorizeByType(int type){
		
		if(mAuthorizingStateListener!=null){
			mAuthorizingStateListener.authrizeAction(AuthorizingStateListener.AUTHORIZING, "authorizing");
		}
		
		switch (type) {
			case SINA_WEIBO_TYPE:
				authorize(ShareSDK.getPlatform(mContext,SinaWeibo.NAME),type);
				break;
			case TENCENT_WEIBO_TYPE:
				authorize(ShareSDK.getPlatform(mContext,TencentWeibo.NAME),type);
				break;
			case TENCENT_QQ_TYPE:
				authorize(ShareSDK.getPlatform(mContext,QZone.NAME),type);
				break;
			case TENCENT_WEIXIN_TYPE:
				//TODO login by weixin
				authorizeByWeiXin(mContext,type);
				break;
	
			default:
				break;
		}
	}
	
	@Override
	public boolean isSNSAuth(int type) {
		
		switch (type) {
		case SINA_WEIBO_TYPE:
			return ShareSDK.getPlatform(mContext,SinaWeibo.NAME).isValid();
		case TENCENT_WEIBO_TYPE:
			return ShareSDK.getPlatform(mContext,TencentWeibo.NAME).isValid();
		case TENCENT_QQ_TYPE:
			return ShareSDK.getPlatform(mContext,QZone.NAME).isValid();
		default:
			break;
		}
		return false;
	}

	@Override
	public void CancelAuthSNS(int type) {
		Platform platfrom = null;
		switch (type) {
		case SINA_WEIBO_TYPE:
			platfrom = ShareSDK.getPlatform(mContext,SinaWeibo.NAME);
			break;
		case TENCENT_WEIBO_TYPE:
			platfrom = ShareSDK.getPlatform(mContext,TencentWeibo.NAME);
			break;
		case TENCENT_QQ_TYPE:
			platfrom = ShareSDK.getPlatform(mContext,QZone.NAME);
			break;
		default:
			break;
		}
		
		if(platfrom!=null&&platfrom.isValid()){
			platfrom.removeAccount();
			platfrom = null;
		}
	}
	
	/**
	 * 清除所有授权
	 */
	public void CancelAllAuthSNS(){
		CancelAuthSNS(ISNSLoginManager.SINA_WEIBO_TYPE);
		CancelAuthSNS(ISNSLoginManager.TENCENT_QQ_TYPE);
		CancelAuthSNS(ISNSLoginManager.TENCENT_WEIBO_TYPE);
	}
	
	@Override
	public SNSUserInfo getSNSUserInfo(int type){
		Platform platfrom = null;
		SNSUserInfo userInfo = null;
		switch (type) {
		case SINA_WEIBO_TYPE:
			platfrom = ShareSDK.getPlatform(mContext,SinaWeibo.NAME);
			userInfo = getUserInfo(SINA_WEIBO_TYPE, platfrom, null);
			break;
		case TENCENT_WEIBO_TYPE:
			platfrom = ShareSDK.getPlatform(mContext,TencentWeibo.NAME);
			userInfo = getUserInfo(SINA_WEIBO_TYPE, platfrom, null);
			break;
		case TENCENT_QQ_TYPE:
			platfrom = ShareSDK.getPlatform(mContext,QZone.NAME);
			userInfo = getUserInfo(SINA_WEIBO_TYPE, platfrom, null);
			break;
		default:
			break;
		}
		return userInfo;
	}
	
	private void authorize(Platform plat,int type) {
		if (plat == null) {
			return;
		}
		
		WebViewUtil.removeCookies(mContext);
		
		if(plat.isValid()) {
			plat.removeAccount();
		}
		
		//第三方授权页开关打开
		MyAuthorizeAdapter.open = true;
		mHandler.removeMessages(STOP_SNS);
		mHandler.sendEmptyMessageDelayed(STOP_SNS, 10000l);
		SNSPageOpening = true;
		
		plat.setPlatformActionListener(new MPlatformActionListener(type));
		plat.SSOSetting(true);
		plat.showUser(null);
	}
	
	/**
	 * 微信登陆授权
	 * @param context
	 * @param type
	 */
	private void authorizeByWeiXin(Context context,int type){
		WeiXinShareUtil.getInstance(mContext).login(mAuthorizingStateListener);
	}
	
	
	/**
	 * 获取用户信息
	 * @param platform
	 * @param res
	 * @return
	 */
	private SNSUserInfo getUserInfo(int type,Platform platform,HashMap<String, Object> res ){
		
		SNSUserInfo user = new SNSUserInfo();
		
		if(platform.isValid()){
			
			user.snsType = type;
			user.expiresIn = String.valueOf(platform.getDb().getExpiresIn());
			user.expiresTime = String.valueOf(platform.getDb().getExpiresTime());
			user.accessToken = platform.getDb().getToken();
			user.headPic = platform.getDb().getUserIcon();
			user.nickName = platform.getDb().getUserName();
			user.thirdPlatformID = platform.getDb().getUserId();
			
//		            String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(
//		                    new java.util.Date(System.currentTimeMillis()+(Long.valueOf(user.expiresIn)*1000)));
//		            System.out.println(date);
//		            date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(
//		            		new java.util.Date(Long.valueOf(user.expiresTime)));
//		            System.out.println(date);
		            
		}
		return user;
	}
	
	private class MPlatformActionListener implements PlatformActionListener{

		private int mtype = 0;
		
		public MPlatformActionListener(int type){
			super();
			mtype = type;
		}
		
		@Override
		public void onComplete(Platform platform, int action,HashMap<String, Object> res) {
			
			switch (action) {
			// 授权成功  解析用户信息 返给登录页
			case Platform.ACTION_USER_INFOR: 
				SNSPageOpening = false;
				L.v(TAG, "onComplete", "ACTION_USER_INFOR");
				if(mAuthorizingStateListener!=null){
					mHandler.obtainMessage(ONOTHERAUTHIRSUCCESS, "authorize success").sendToTarget();
				}
				SNSUserInfo userInfo = getUserInfo(mtype,platform,res);
				if(platform.getName().equals(QZone.NAME)||platform.getName().equals(TencentWeibo.NAME)){
					WebViewUtil.removeCookies(mContext);
				}
				platform.removeAccount();
				//回调接口  将用户信息返回给登录页面
				if(mAuthorizingStateListener!=null){
					mHandler.obtainMessage(GETUSERINFOSUCCESS, userInfo).sendToTarget();
				}
				break;

			default:
				break;
			}
		}
		
		@Override
		public void onCancel(Platform platform, int action) {
			if (action == Platform.ACTION_USER_INFOR) {
				SNSPageOpening = false;
				L.v(TAG, "onCancel", "ACTION_USER_INFOR");
				// 取消授权  回调接口
				if(mAuthorizingStateListener!=null){
					mHandler.obtainMessage(ONOTHERAUTHIRCANCLE, "authorize cancel").sendToTarget();
				}
				platform.removeAccount();
			}
		}

		@Override
		public void onError(Platform platform, int action, Throwable t) {
			SNSPageOpening = false;
			L.v(TAG, "onError", "error info : " + t.getMessage());
			
			//授权出错  回调接口
			if(mAuthorizingStateListener!=null){
				mHandler.obtainMessage(ONOTHERAUTHIRERROR, "authorize error").sendToTarget();
			}
			platform.removeAccount();
		}
	}
}
